﻿///***************************************************************
/// 시  스  템 : Updms.Etc
/// 단위시스템 : ETC
/// 계      층 : Presentation Layer
/// 프로그램명 : Etc4010b
/// 파  일  명 : Etc4010b.aspx.cs
/// 설      명 : 구글캘린더 일괄업로드
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2012-04-05 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Threading;

using SMFramework.Utility;

using Base.AppFramework;
using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Etc.Exe;
using System.Web;


namespace Updms.Etc
{
	public partial class Etc4010b : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Etc4010b";
		Global global = new Global();

		CommCode.Etc etc = new CommCode.Etc(LANG_SET);
		AccessCheck access = new AccessCheck();

		// 페이지모드
		private string gs_page_mode = "";

		protected string gs_source = "";

		#endregion

		#region Page_Load

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//최초 화면 로딩시 처리해야 할 부분
				SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			}
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region CRUD (CheckFileStatus, InsertProcess)

		//파일상태체크
		private void CheckFileStatus()
		{
			StringBuilder sb = new StringBuilder();

			string ae001_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE001;
			string ae002_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE002;
			string ae003_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE003;
			string ae004_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE004;
			string ae005_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE005;
			string ae006_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE006;

			string ae001_class = "";
			string ae002_class = "";
			string ae003_class = "";
			string ae004_class = "";
			string ae005_class = "";
			string ae006_class = "";

			ae001_class = (FileUtil.IsFileExist(ae001_path)) ? "status_on" : "status_off";
			ae002_class = (FileUtil.IsFileExist(ae002_path)) ? "status_on" : "status_off";
			ae003_class = (FileUtil.IsFileExist(ae003_path)) ? "status_on" : "status_off";
			ae004_class = (FileUtil.IsFileExist(ae004_path)) ? "status_on" : "status_off";
			ae005_class = (FileUtil.IsFileExist(ae005_path)) ? "status_on" : "status_off";
			ae006_class = (FileUtil.IsFileExist(ae006_path)) ? "status_on" : "status_off";

			sb.AppendLine("<div class=\"" + ae001_class + "\">개인업무 [" + FileUtil.GetLastWriteTime(ae001_path) + "][" + FILE_NAME_CAL_AE001 + "]</div>");
			sb.AppendLine("<div class=\"" + ae002_class + "\">가족업무 [" + FileUtil.GetLastWriteTime(ae002_path) + "][" + FILE_NAME_CAL_AE002 + "]</div>");
			sb.AppendLine("<div class=\"" + ae003_class + "\">본사업무 [" + FileUtil.GetLastWriteTime(ae003_path) + "][" + FILE_NAME_CAL_AE003 + "]</div>");
			sb.AppendLine("<div class=\"" + ae004_class + "\">프로젝트 [" + FileUtil.GetLastWriteTime(ae004_path) + "][" + FILE_NAME_CAL_AE004 + "]</div>");
			sb.AppendLine("<div class=\"" + ae005_class + "\">개발일정 [" + FileUtil.GetLastWriteTime(ae005_path) + "][" + FILE_NAME_CAL_AE005 + "]</div>");
			sb.AppendLine("<div class=\"" + ae006_class + "\">트레이닝 [" + FileUtil.GetLastWriteTime(ae006_path) + "][" + FILE_NAME_CAL_AE006 + "]</div>");

			lbl_file_status.Text = sb.ToString();

			gs_page_mode = "R";
		}

		//저장
		private void InsertProcess()
		{
			try
			{
				string[] la_local_files = Directory.GetFiles(FILE_PATH_UPLOAD_CALENDAR_BATCH, "*.ics");

				if (la_local_files.Length > 0)
				{
					for (int i = 0; i < la_local_files.Length; i++)
					{
						string ls_xml = "";
						
						FileInfo fi = new FileInfo(la_local_files[i]);
						string ls_file_name = fi.Name;

						if (ls_file_name == FILE_NAME_CAL_AE001)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE001;
							ls_xml = SetValue("AE001");
						}
						else if (ls_file_name == FILE_NAME_CAL_AE002)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE002;
							ls_xml = SetValue("AE002");
						}
						else if (ls_file_name == FILE_NAME_CAL_AE003)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE003;
							ls_xml = SetValue("AE003");
						}
						else if (ls_file_name == FILE_NAME_CAL_AE004)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE004;
							ls_xml = SetValue("AE004");
						}
						else if (ls_file_name == FILE_NAME_CAL_AE005)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE005;
							ls_xml = SetValue("AE005");
						}
						else if (ls_file_name == FILE_NAME_CAL_AE006)
						{
							gs_source = FILE_PATH_UPLOAD_CALENDAR_BATCH + FILE_NAME_CAL_AE006;
							ls_xml = SetValue("AE006");
						}

						if (ls_xml != "")
						{
							//저장
							using (Etc4010b_RT _Etc4010b_RT = new Etc4010b_RT())
							{
								int li_return = _Etc4010b_RT.InsertProcess(ls_xml);
								string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
								string ls_msg_tp = (li_return > 0) ? "ICR" : "AC";

								if (i == (la_local_files.Length - 1))
								{
									CallMsgBoxInAjax(ls_msg_id, null, ls_msg_tp);
								}
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		#endregion

		#region SetValue

		//데이터 파싱
		private string SetValue(string category)
		{
			/*
			X-WR-CALNAME:프로젝트								//Category
				BEGIN:VEVENT
					DTSTART;TZID=Etc/GMT-9:20111018T100000	//St_Dt
					DTEND;TZID=Etc/GMT-9:20111018T113000	//Ed_Dt
					DESCRIPTION:							//Contents
					LOCATION:프라임타워 7F Smart Office 703호	//Location
					STATUS:CONFIRMED						//Status
					SUMMARY:SM공유회의						//Title
				END:VEVENT

			AE001 개인업무 "relic4160@gmail.com.ics";
			AE002 가족업무 "kq2amspf3o72lm23bs2h5c13hc@group.calendar.google.com.ics";
			AE003 본사업무 "a570u33biejhuqus5tpcgaopv0@group.calendar.google.com.ics";
			AE004 프로젝트 "a69ncp5du77qv7cpu5pkqg1g4c@group.calendar.google.com.ics";
			AE005 개발일정 "r3bk87l21r4fsj0t4m23k15tps@group.calendar.google.com.ics";
			AE006 트레이닝 "cb8e9pqfq2cvt2oa9vv2dcr2d0@group.calendar.google.com.ics";

			*/
			StringBuilder sb = new StringBuilder();
			try
			{
				FileStream fs = new FileStream(gs_source, FileMode.OpenOrCreate, FileAccess.Read);
				StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);
				sr.BaseStream.Seek(0, SeekOrigin.Begin);

				string begin = "BEGIN:VEVENT";
				
				string st_dt1 = "DTSTART;VALUE=DATE:";
				string st_dt2 = "DTSTART:";
				string st_dt3 = "DTSTART;TZID=Etc/GMT-9:";
				string st_dt4 = "DTSTART;TZID=Asia/Seoul:";
				
				string ed_dt1 = "DTEND;VALUE=DATE:";
				string ed_dt2 = "DTEND:";
				string ed_dt3 = "DTEND;TZID=Etc/GMT-9:";
				string ed_dt4 = "DTEND;TZID=Asia/Seoul:";

				string title = "SUMMARY:";
				string contents = "DESCRIPTION:";
				string last_modified = "LAST-MODIFIED:";
				string alarm = "This is an event reminder"; //DESCRIPTION에 이 문자가 있으면 알림이다
				string location = "LOCATION:";

				string end = "END:VEVENT";

				sb.AppendLine("<UPDMS>");

				while (sr.Peek() > -1)
				{
					string ls_line = sr.ReadLine();
					string ls_parse = "";

					if (ls_line == begin)
					{
						sb.AppendLine("<UPDMS_ETC_PLANNER>");
					}
					else if (ls_line.Contains(st_dt1))
					{
						ls_parse = ls_line.Substring(st_dt1.Length, ls_line.Length - st_dt1.Length);

						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						if (ls_dt != "1970-01-01")
						{
							sb.AppendLine("<St_Dt><![CDATA[" + ls_dt + "]]></St_Dt>");
							sb.AppendLine("<St_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 9, ls_m) + "]]></St_Hm>");
						}
					}
					else if (ls_line.Contains(st_dt2))
					{
						ls_parse = ls_line.Substring(st_dt2.Length, ls_line.Length - st_dt2.Length);

						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						if (ls_dt != "1970-01-01")
						{
							sb.AppendLine("<St_Dt><![CDATA[" + ls_dt + "]]></St_Dt>");
							sb.AppendLine("<St_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 9, ls_m) + "]]></St_Hm>");
						}
					}
					else if (ls_line.Contains(st_dt3))
					{
						ls_parse = ls_line.Substring(st_dt3.Length, ls_line.Length - st_dt3.Length);

						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						if (ls_dt != "1970-01-01")
						{
							sb.AppendLine("<St_Dt><![CDATA[" + ls_dt + "]]></St_Dt>");
							sb.AppendLine("<St_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 0, ls_m) + "]]></St_Hm>");	//GMT적용되어 있으므로
						}
					}
					else if (ls_line.Contains(st_dt4))
					{
						ls_parse = ls_line.Substring(st_dt4.Length, ls_line.Length - st_dt4.Length);

						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						if (ls_dt != "1970-01-01")
						{
							sb.AppendLine("<St_Dt><![CDATA[" + ls_dt + "]]></St_Dt>");
							sb.AppendLine("<St_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 0, ls_m) + "]]></St_Hm>");	//GMT적용되어 있으므로
						}
					}
					else if (ls_line.Contains(ed_dt1))
					{
						ls_parse = ls_line.Substring(ed_dt1.Length, ls_line.Length - ed_dt1.Length);
						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);
						ls_dt = DateUtil.GetCalcDay(ls_dt, -1, "yyyy-MM-dd");	//하루짜리 종일일정은 종료일이 +1일로 되어있다.

						sb.AppendLine("<Ed_Dt><![CDATA[" + ls_dt + "]]></Ed_Dt>");
						sb.AppendLine("<Ed_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 9, ls_m) + "]]></Ed_Hm>");
					}
					else if (ls_line.Contains(ed_dt2))
					{
						ls_parse = ls_line.Substring(ed_dt2.Length, ls_line.Length - ed_dt2.Length);

						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						sb.AppendLine("<Ed_Dt><![CDATA[" + ls_dt + "]]></Ed_Dt>");
						sb.AppendLine("<Ed_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 9, ls_m) + "]]></Ed_Hm>");
					}
					else if (ls_line.Contains(ed_dt3))
					{
						ls_parse = ls_line.Substring(ed_dt3.Length, ls_line.Length - ed_dt3.Length);
						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						sb.AppendLine("<Ed_Dt><![CDATA[" + ls_dt + "]]></Ed_Dt>");
						sb.AppendLine("<Ed_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 0, ls_m) + "]]></Ed_Hm>");	//GMT적용되어 있으므로
					}
					else if (ls_line.Contains(ed_dt4))
					{
						ls_parse = ls_line.Substring(ed_dt4.Length, ls_line.Length - ed_dt4.Length);
						string ls_dt = (ls_parse.Length > 8) ? ls_parse.Substring(0, 8) : ls_parse;
						string ls_h = (ls_parse.Length > 11) ? ls_parse.Substring(9, 2) : "--";
						string ls_m = (ls_parse.Length > 13) ? ls_parse.Substring(11, 2) : "--";

						ls_dt = DateUtil.FormatDate(ls_dt);

						sb.AppendLine("<Ed_Dt><![CDATA[" + ls_dt + "]]></Ed_Dt>");
						sb.AppendLine("<Ed_Hm><![CDATA[" + DateUtil.ConvertHourFormat(ls_h, 0, ls_m) + "]]></Ed_Hm>");	//GMT적용되어 있으므로
					}
					else if (ls_line.Contains(title))
					{
						ls_parse = ls_line.Substring(title.Length, ls_line.Length - title.Length);
						ls_parse = ls_parse.Replace("\\n", "^n");
						ls_parse = ls_parse.Replace("\\", "");
						sb.AppendLine("<Title><![CDATA[" + ls_parse + "]]></Title>");
					}
					else if (ls_line.Contains(contents) && !ls_line.Contains(alarm))
					{
						//DESCRIPTION: ~ LAST-MODIFIED:
						string ls_contents = "";
						string ls_contents_1st = "";
						string ls_contents_next = "";
						string ls_contents_by = "";

						ls_contents_1st = ls_line.Substring(contents.Length, ls_line.Length - contents.Length);

						if (ls_contents_1st.Length > 0)
						{
							for (int i = 0; i < 100; i++)
							{
								ls_contents_next = sr.ReadLine();

								if (ls_contents_next != null)
								{
									if (ls_contents_next.Contains(last_modified))
									{
										i = 100; //for문 빠져나간다
									}
									else
									{
										ls_contents_next = ls_contents_next.TrimStart(); //앞 공백 제거
										ls_contents_by = ls_contents_by + ls_contents_next;
									}
								}
							}
							ls_contents = ls_contents_1st + ls_contents_by;
						}

						ls_contents = ls_contents.Replace("\\n", "^n");
						ls_contents = ls_contents.Replace("\\", "");
						sb.AppendLine("<Contents><![CDATA[" + ls_contents + "]]></Contents>");
					}
					else if (ls_line.Contains(location) && !ls_line.Contains("X-LIC-LOCATION:"))
					{
						ls_parse = ls_line.Substring(location.Length, ls_line.Length - location.Length);
						ls_parse = ls_parse.Replace("\\n", "^n");
						ls_parse = ls_parse.Replace("\\", "");
						sb.AppendLine("<Location><![CDATA[" + ls_parse + "]]></Location>");
					}
					else if (ls_line == end)
					{
						sb.AppendLine("<Category><![CDATA[" + category + "]]></Category>");
						sb.AppendLine("<Create_User><![CDATA[" + USER_ID + "]]></Create_User>");
						sb.AppendLine("</UPDMS_ETC_PLANNER>");
					}
				}

				sb.AppendLine("</UPDMS>");
			}
			catch (Exception e)
			{
				SMEventLog.WriteExceptionLog(e);
			}

			return sb.ToString();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//접근권한 체크
				if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
				{
					Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
				}
				//사용권한별 버튼처리
				PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					ibtn_save.Visible = false;
					break;
				case "R":	// 업로드 클릭후 파일 있을때
					ibtn_save.Visible = access.CheckPgmUsingGrant(USER_DIV, PID);
					break;
			}
		}

		#endregion

		#region File (UploadFile, ExecFile)

		private void UploadFile()
		{
			try
			{
				HttpFileCollection addFile = HttpContext.Current.Request.Files;

				if (addFile.Count > 0 && addFile[0].ContentLength > 0)
				{
					int size = addFile[0].ContentLength;
					string ls_file_name = addFile[0].FileName; //파일이름
					string ls_file_path = FILE_PATH_UPLOAD_CALENDAR_BATCH + ls_file_name; //파일경로

					//파일명 체크 web.config와 비교
					if (ls_file_name == FILE_NAME_CAL_ZIP)
					{
						addFile[0].SaveAs(ls_file_path);

						if (FileUtil.IsFileExist(ls_file_path))
						{
							//업로드된 압축파일풀기
							//7-Zip이 설치되어 있어야 한다.(7-zip.org)
							ExecFile("UPDMS_Extract_ICS.bat", FILE_NAME_CAL_ZIP);
						}
					}
					else
					{
						CallMsgBoxInAjax("MSG_ERR_190");	//구글캘린더 파일이 아닙니다
					}
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_177");	//업로드할 파일을 선택하세요
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		//파일실행
		private void ExecFile(string ls_file_nm, string ls_arguments)
		{
			string ls_file_url = FILE_PATH_UPLOAD_BATCH + ls_file_nm;	//bat파일 위치

			try
			{
				if (FileUtil.IsFileExist(ls_file_url))
				{
					Process p = new Process();

					p.StartInfo.FileName = ls_file_url;
					p.StartInfo.Arguments = ls_arguments;
					p.StartInfo.CreateNoWindow = true;

					p.Start();
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_124");	//실행할 파일이 없습니다
				}
			}
			catch (Exception e)
			{
				SMEventLog.WriteErrorLog(e.ToString());
				CallMsgBoxInAjax("MSG_ERR_128");	//파일을 실행하지 못했습니다
			}
		}

		#endregion		

		#region 버튼이벤트

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			InsertProcess();
		}

		//업로드
		protected void ibtn_upload_Click(object sender, EventArgs e)
		{
			UploadFile();
			CheckFileStatus();
		}

		//파일상태 새로고침
		protected void lbtn_file_Status_Click(object sender, EventArgs e)
		{
			CheckFileStatus();
		}

		#endregion

	}
}
